package cn.bingoo.handy;

import java.io.StringWriter;

import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

/**
 * Pretty-prints xml, supplied as a string.
 * <p/>
 * eg.
 * <code>
 * String formattedXml = new XmlFormatter().format("<tag><nested>hello</nested></tag>");
 * </code>
 */
public class XmlFormatter {
    public static String prettyPrint(final String xml) {
        return prettyPrint(xml, "        ");
    }

    public static String prettyPrint(final String xml, String indent) {
        final StringWriter sw;

        try {
            final OutputFormat format = OutputFormat.createPrettyPrint();
            format.setIndent(indent);
            final org.dom4j.Document document = DocumentHelper.parseText(xml);
            sw = new StringWriter();
            final XMLWriter writer = new XMLWriter(sw, format);
            writer.write(document);
        }
        catch (Exception e) {
            throw new RuntimeException("Error pretty printing xml:\n" + xml, e);
        }
        return sw.toString();
    }

    /**
     * 生成紧凑的XML字符串。
     * @param doc XML文档对象
     * @return XML字符串
     */
    public static String compactFormat(final String xml) {
        OutputFormat format = OutputFormat.createCompactFormat();
        format.setNewLineAfterDeclaration(false);
        format.setTrimText(true);
        StringWriter swriter = new StringWriter();
        XMLWriter writer = new XMLWriter(swriter, format);
        try {
            final org.dom4j.Document doc = DocumentHelper.parseText(xml);
            writer.write(doc);
            writer.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return swriter.toString();
    }

    public static void main(String[] args) {
        String prettyFormat = prettyPrint("<root><child>aaa</child><child/></root>");
        System.out.println(prettyFormat);

        String unformattedXml =
                "<?xml version=\"1.0\" encoding=\"UTF-8\"?><QueryMessage\n" +
                        "        xmlns=\"http://www.SDMX.org/resources/SDMXML/schemas/v2_0/message\"\n" +
                        "        xmlns:query=\"http://www.SDMX.org/resources/SDMXML/schemas/v2_0/query\">\n" +
                        "    <Query>\n" +
                        "        <query:CategorySchemeWhere>\n" +
                        "   \t\t\t\t\t         <query:AgencyID>ECB\n\n\n\n</query:AgencyID>\n" +
                        "        </query:CategorySchemeWhere>\n" +
                        "    </Query>\n\n\n\n\n" +
                        "</QueryMessage>";

        System.out.println(prettyPrint(unformattedXml));
    }

}
